package com.hzit.mmcb.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzit.common.exception.Assert;
import com.hzit.common.result.ResponseEnum;
import com.hzit.mmcb.core.enums.LendStatusEnum;
import com.hzit.mmcb.core.enums.TransTypeEnum;
import com.hzit.mmcb.core.hfb.FormHelper;
import com.hzit.mmcb.core.hfb.HfbConst;
import com.hzit.mmcb.core.hfb.RequestHelper;
import com.hzit.mmcb.core.pojo.entity.*;
import com.hzit.mmcb.core.mapper.LendReturnMapper;
import com.hzit.mmcb.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.mmcb.core.utils.LendNoUtils;
import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.util.resources.cldr.nso.CalendarData_nso_ZA;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 还款记录表 服务实现类
 * </p>
 *
 * @author ljh
 * @since 2024-08-27
 */
@Service
public class LendReturnServiceImpl extends ServiceImpl<LendReturnMapper, LendReturn> implements LendReturnService {
    @Autowired
    private LendService lendService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private LendItemReturnService lendItemReturnService;
    @Autowired
    private TransFlowService transFlowService;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private LendItemService lendItemService;
    @Autowired
    private UserBindService userBindService;

    @Override
    public List<LendReturn> listByLendId(Long id) {
        return this.list(new LambdaQueryWrapper<LendReturn>().eq(LendReturn::getLendId,id));
    }

    @Override
    public String commitReturn(Long lendReturnId, Long userId) {
        LendReturn lendReturn = this.getById(lendReturnId);
        Lend lend = lendService.getById(lendReturn.getLendId());
        UserInfo userInfo = userInfoService.getById(lend.getUserId());
        UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, userInfo.getId()));
        //判断余额是否充足
        Assert.isTrue(userAccount.getAmount().doubleValue()>=lendReturn.getTotal().doubleValue(), ResponseEnum.NOT_SUFFICIENT_FUNDS_ERROR);
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentGoodsName",lend.getTitle());
        paramMap.put("agentBatchNo", lendReturn.getReturnNo());
        paramMap.put("fromBindCode",userInfo.getBindCode());
        paramMap.put("totalAmt",lendReturn.getBaseAmount());
        paramMap.put("note","");
        String bindCode = userBindService.getOne(new LambdaQueryWrapper<UserBind>().eq(UserBind::getUserId,userInfo.getId())).getBindCode();
        //获取还款列表表单
        List<Map<String,Object>> lendItemReturnDetailList=lendItemReturnService.addReturnDetail(lendReturnId);
        paramMap.put("agentId", HfbConst.AGENT_ID);
        //商户商品名称
        paramMap.put("agentGoodsName", lend.getTitle());
        //批次号
        paramMap.put("agentBatchNo",lendReturn.getReturnNo());
        //还款⼈绑定协议号
        paramMap.put("fromBindCode", bindCode);
        //还款总额
        paramMap.put("totalAmt", lendReturn.getTotal());
        paramMap.put("note", "");
        //还款明细
        paramMap.put("data", JSONObject.toJSONString(lendItemReturnDetailList)
        );
        paramMap.put("voteFeeAmt", new BigDecimal(0));
        paramMap.put("notifyUrl", HfbConst.BORROW_RETURN_NOTIFY_URL);
        paramMap.put("returnUrl", HfbConst.BORROW_RETURN_RETURN_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(paramMap);
        paramMap.put("sign", sign);
        String formStr = FormHelper.buildForm(HfbConst.BORROW_RETURN_URL, paramMap);
        return formStr;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String notifyReturn(Map<String, Object> map) {
        String agentBatchNo = (String) map.get("agentBatchNo");
        //幂等性处理
        TransFlow transFlow = transFlowService.getOne(new LambdaQueryWrapper<TransFlow>().eq(TransFlow::getTransNo, agentBatchNo));
        if (transFlow!=null){
            return "success";
        }
        //获取map中的信息
        String voteFeeAmt = (String)map.get("voteFeeAmt");
        //修改还款计划信息
        LendReturn lendReturn = this.getOne(new LambdaQueryWrapper<LendReturn>().eq(LendReturn::getReturnNo, agentBatchNo));
        //更新还款状态
        lendReturn.setStatus(1);
        lendReturn.setRealReturnTime(LocalDateTime.now());
        lendReturn.setFee(new BigDecimal(voteFeeAmt));
        this.updateById(lendReturn);

        //更新标的状态
        Lend lend = lendService.getById(lendReturn.getLendId());
        if (lend.getPeriod()==lendReturn.getCurrentPeriod()){
            lend.setStatus(LendStatusEnum.PAY_OK.getStatus());
        }
        //修改还款人账户信息
        BigDecimal totalAmt = new BigDecimal((String)map.get("totalAmt"));
        UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, lend.getUserId()));
        userAccount.setAmount(userAccount.getAmount().subtract(totalAmt));
        userAccountService.updateById(userAccount);
        //生产流水
        UserInfo userInfo = userInfoService.getById(lend.getUserId());
        transFlow = new TransFlow();
        transFlow.setUserId(userInfo.getId());
        transFlow.setUserName(userInfo.getName());
        transFlow.setTransNo(agentBatchNo);
        transFlow.setTransType(TransTypeEnum.WITHDRAW.getIntegral());
        transFlow.setTransTypeName(TransTypeEnum.WITHDRAW.getMsg());
        transFlow.setTransAmount(totalAmt);
        transFlow.setMemo("提现");
        transFlowService.save(transFlow);

        //修改投资人账户信息
        List<LendItemReturn> lendItemReturnList = lendItemReturnService.list(new LambdaQueryWrapper<LendItemReturn>().eq(LendItemReturn::getLendReturnId, lendReturn.getId()));
        for (LendItemReturn lendItemReturn : lendItemReturnList) {
            //修改回款计划状态
            lendItemReturn.setStatus(1);
            lendItemReturn.setRealReturnTime(LocalDateTime.now());
            lendItemReturnService.updateById(lendItemReturn);
            //修改投资项信息
            LendItem lendItem = lendItemService.getById(lendItemReturn.getLendItemId());
            lendItem.setRealAmount(lendItemReturn.getInterest());
            lendItemService.updateById(lendItem);

            //修改用户信息
            UserAccount userAccountServiceOne= userAccountService.getOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, lendItem.getInvestUserId()));
            userAccountServiceOne.setAmount(userAccountServiceOne.getAmount().add(lendItemReturn.getTotal()));
            userAccountService.updateById(userAccountServiceOne);

            //添加流水信息
            UserInfo userInfo1 = userInfoService.getById(userAccount.getUserId());
            transFlow = new TransFlow();
            transFlow.setUserId(userInfo1.getId());
            transFlow.setUserName(userInfo1.getName());
            transFlow.setTransNo(LendNoUtils.getReturnItemNo());
            transFlow.setTransType(TransTypeEnum.INVEST_BACK.getIntegral());
            transFlow.setTransTypeName(TransTypeEnum.INVEST_BACK.getMsg());
            transFlow.setTransAmount(lendItemReturn.getTotal());
            transFlow.setMemo("还款到账，项⽬编号：" + lend.getLendNo() + "，项⽬名称：" + lend.getTitle());
            transFlowService.save(transFlow);
        }
        return "success";
    }
}
